<template>
	<view class="container">
		<!-- 订单状态筛选条 -->
		<view class="filter-tabs">
			<view class="tab-item" :class="{ active: currentFilter === index }" v-for="(tab, index) in filterTabs"
				:key="index" @click="switchFilter(index)">
				{{ tab }}
				<view v-if="showBadge(index)" class="badge">{{ tabCounts[index] }}</view>
			</view>
		</view>

		<!-- 订单列表 -->
		<view class="order-list">
			<view class="order-item" v-for="(order, index) in filteredOrders" :key="index">
				<!-- 订单编号 -->
				<view class="order-number">
					<text class="orderNumberHui">订单号：{{ order.order_no }}</text>
					<text class="order-status">{{ orderStatusText(order.status) }}</text>
				</view>

				<!-- 商品信息 -->
				<view class="product-info">
					<image class="product-image" :src="order.product_image" mode="aspectFill" />
					<view class="product-details">
						<view class="product-name">{{ order.product_name }}</view>
						<view class="product-spec">规格：{{ order.spec }}</view>
						<view class="product-quantity">数量：{{ order.quantity }}</view>
					</view>
					<view class="points">{{ order.points }}积分</view>
				</view>

				<!-- 操作按钮 -->
				<view class="action-buttons">
					<button class="btn-view" @click="viewOrder(order)">查看订单</button>
					<button class="btn-action" :class="getActionClass(order.status)" @click="handleAction(order)"
						:disabled="order.status === 2 || order.status === 4">
						{{ getActionText(order.status) }}
					</button>
				</view>
			</view>

			<view v-if="filteredOrders==null || filteredOrders.length==0" style="
					padding: 11px;    
					font-size: 14px;
					color: #333;
					width:93%;
					background-color: #fff;
				">
				什么都没有
			</view>

		</view>
	</view>
</template>

<script setup>
	import {
		passenger
	} from '@/api/index.js';
	import {
		ref,
		computed,
		onMounted
	} from 'vue';
	import {
		onLoad,
		onShow,
		onUnload
	} from '@dcloudio/uni-app'
	import {
		useStore
	} from '@/store/counter.js';
	
	const storeObj = useStore();

	// 订单状态文本映射
	const statusTextMap = {
		0: '待发货',
		1: '待收货',
		2: '已完成',
		3: '自提详情',
		4: '已完成'
	};



	// 当前选中的筛选条件
	const currentFilter = ref(0);

	// 筛选标签列表
	const filterTabs = ['全部', '待发货', '待收货', '待自提', '已完成'];

	// 切换筛选条件
	const switchFilter = (index) => {
		currentFilter.value = index;
	};

	// 模拟订单数据
	const orders = ref([{
			order_no: 'AW123456789',
			product_image: 'https://aw2025ht.kangye.xyz/api/profile/upload/sku1.png',
			product_name: '立美丝凡士林保湿霜干润肤霜身体乳',
			points: 199,
			spec: '250g',
			quantity: 1,
			status: 0 // 待发货
		},
		{
			order_no: 'AW123456790',
			product_image: 'https://via.placeholder.com/150x150',
			product_name: '炫迈爽美白牙膏按压款',
			points: 99,
			spec: '100g',
			quantity: 1,
			status: 1 // 待收货
		},
		{
			order_no: 'AW123456791',
			product_image: 'https://via.placeholder.com/150x150',
			product_name: '测试已完成商品',
			points: 50,
			spec: '150g',
			quantity: 1,
			status: 2 // 已完成
		},
		{
			order_no: 'AW123456792',
			product_image: 'https://via.placeholder.com/150x150',
			product_name: '测试待自提商品',
			points: 75,
			spec: '200g',
			quantity: 1,
			status: 3 // 待自提
		},
		{
			order_no: 'AW123456793',
			product_image: 'https://via.placeholder.com/150x150',
			product_name: '测试已取货商品',
			points: 80,
			spec: '250g',
			quantity: 1,
			status: 4 // 已完成
		}
	]);



	function transformOrders(orders) {
		return orders.map(order => {
			// 提取商品信息
			const product = order.spList && order.spList.length > 0 ? order.spList[0] : {};

			// 创建新订单对象
			const newOrder = {
				order_no: order.orderNo,
				product_image: product.image || 'https://via.placeholder.com/150x150', // 默认图片
				product_name: product.name || '默认商品名称',
				points: product.jiFen || 0,
				spec: product.guiGe || '默认规格',
				quantity: 1, // 默认数量
				status: order.status
			};

			// 保留原始订单中没有的新订单中没有的字段
			const remainingFields = Object.keys(order).reduce((acc, key) => {
				if (!newOrder.hasOwnProperty(key) && key !== 'spList') {
					acc[key] = order[key];
				}
				return acc;
			}, {});

			// 合并新订单对象和剩余字段
			return {
				...newOrder,
				...remainingFields
			};
		});
	}


	onUnload(() => {
		wx.reLaunch({
			url: '/package/pages/qianDaoYe/qianDaoYe'
		});
	})

const orderInfo = ref({
		userName: '王丽',
		userPhone: '139****2222',
		userProvince: '河北省',
		userCity: '邯郸市',
		userDistrict: '丛台区',
		userAddress: '广安路广安小区',
		orderNo: 'AW123456789',
		orderTime: '2025-03-11 14:48:23',
		status: 0, // 0: 待收货, 1: 待自提, 2: 已取货
		pickupTime: '2025.3.1-2025.3.31',
		pickupPhone: '13911112222',
		pickupAddress: '河北省邯郸市经济开发区美的路113号',
		product_image: 'https://aw2025ht.kangye.xyz/api/profile/upload/RTkJqu4KOxiy.png',
		product_name: '立美丝凡士林保湿霜干皮润肤霜身体乳',
		spec: '250g',
		quantity: 1,
		points: 199
	});

	onLoad(async () => {
		// 页面加载的时候，读取数据库数据，读取用户所有的订单，交给页面
		let res = await passenger.selectAllOrderById();
		console.log(res)
		console.log(res.data)
		// 赋值
		// 转换后的订单对象数组
		const transformedOrders = transformOrders(res.data);
		console.log(transformedOrders)
		orders.value = transformedOrders
	})
	// 计算每个筛选标签的订单数量
	const tabCounts = computed(() => {
		const counts = [0, 0, 0, 0, 0];

		orders.value.forEach(order => {
			if (order.status === 0) counts[1]++;
			else if (order.status === 1) counts[2]++;
			else if (order.status === 3) counts[3]++;
			else if (order.status === 2 || order.status === 4) counts[4]++;
		});

		return counts;
	});

	// 判断是否显示角标
	const showBadge = (index) => {
		return index !== 0 && index !== 4 && tabCounts.value[index] > 0;
	};
	// 根据当前筛选条件筛选订单
	const filteredOrders = computed(() => {
		if (currentFilter.value === 0) {
			return orders.value; // 全部订单
		}

		// 根据筛选条件筛选对应状态
		const statusMap = {
			1: 0, // 待发货
			2: 1, // 待收货
			3: 3, // 待自提
			4: [2, 4] // 已完成
		};

		if (currentFilter.value === 4) {
			// 已完成包含 status 2 和 4
			return orders.value.filter(order =>
				statusMap[currentFilter.value].includes(order.status)
			);
		}

		return orders.value.filter(order =>
			order.status === statusMap[currentFilter.value]
		);
	});

	// 获取订单状态文本
	const orderStatusText = (status) => {
		return statusTextMap[status] || '未知状态';
	};

	// 获取操作按钮文本
	const getActionText = (status) => {
		if (status === 0) return '催促发货';
		if (status === 1) return '确认收货';
		if (status === 3) return '去自提';
		return '已完成';
	};

	// 获取操作按钮样式类
	const getActionClass = (status) => {
		if (status === 0 || status === 1 || status === 3) {
			return 'btn-action-pending';
		}
		return 'btn-action-completed';
	};

	// 查看订单详情
	const viewOrder = (order) => {
		console.log('查看订单:', order);
		console.log('查看订单:', order.values);
		// 这里可以跳转到订单详情页面
		//把订单对象放到pinia中
		storeObj.orderObj = order;
		// 跳转到查看订单详情
		uni.navigateTo({
			url: "/packagenew/pages/chaKanDingDanXiangQing/chaKanDingDanXiangQing"
		})
	};

	// 处理订单操作
	const handleAction = (order) => {
		if (order.status === 0) {
			console.log('催促发货:', order);
			// 催促发货逻辑
			// 弹出信息框标识已催促
			uni.showToast({
				title: '催促成功',
				icon: 'success',
				duration: 2000
			});
		} else if (order.status === 1) {
			console.log('确认收货:', order);
			// 修改后台状态为确认收货，为status = 2
			// 确认收货按钮点击事件
			uni.showModal({
				title: '确认收货',
				content: '确认已经收到商品吗？',
				success: async (res) => {
					
					
					
					if (res.confirm) {
						// 更新订单状态
						order.status = 2;
						// 去后台发送请求修改代码
						let asdf = {
							id: order.id,
							okTime: new Date(),
							status: 4,
						}
						let res = await passenger.updateOrderPoints(asdf)
						if (res.code == 200) {
							//成功
							uni.showToast({
								title: '确认收货成功',
								icon: 'success'
							});
						}

					}
				}
			});
			// 确认收货逻辑
		} else if (order.status === 3) {
			console.log('去自提:', order);
			// 进入详情。
			storeObj.orderObj = order;
			// 跳转到查看订单详情
			uni.navigateTo({
				url: "/packagenew/pages/chaKanDingDanXiangQing/chaKanDingDanXiangQing"
			})
			// 自提逻辑
		}
	};
</script>

<style scoped>
	.orderNumberHui {
		color: #aaa;
	}

	.container {
		padding: 20rpx 33rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	/* 筛选标签样式 */
	.filter-tabs {
		display: flex;
		justify-content: space-around;
		margin-bottom: 20rpx;
		background-color: #fff;
		border-radius: 10rpx;
		padding: 10rpx 0;
	}

	.tab-item {
		position: relative;
		padding: 10rpx 20rpx;
		font-size: 30rpx;
		color: #999;
		font-weight: 300;
	}

	.tab-item.active {
		color: #f96c00;
		font-weight: bold;
		border-bottom: 4rpx solid #f96c00;
	}

	/* 角标样式 */
	.badge {
		position: absolute;
		top: -8rpx;
		right: -16rpx;
		background-color: #FF3B30;
		color: #fff;
		font-size: 20rpx;
		width: 32rpx;
		height: 32rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* 订单列表样式 */
	.order-list {
		border-radius: 10rpx;
		margin-top: 20rpx;
	}

	.order-item {
		margin-bottom: 20rpx;
		padding: 20rpx;
		background-color: #fff;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.order-number {
		display: flex;
		justify-content: space-between;
		margin-bottom: 20rpx;
		font-size: 28rpx;
		color: #aaa;
		border-bottom: 1px solid #e8e8e8;
		padding-bottom: 10px;
	}

	.order-status {
		color: #FF6B00;
		font-weight: bold;
	}

	.product-info {
		display: flex;
		margin-bottom: 20rpx;
	}

	.product-image {
		width: 150rpx;
		height: 150rpx;
		border-radius: 10rpx;
		margin-right: 20rpx;
	}

	.product-details {
		flex: 1;
	}

	.product-name {
		font-size: 32rpx;
		margin-bottom: 10rpx;
		color: #333;
	}

	.product-spec,
	.product-quantity {
		font-size: 26rpx;
		color: #999;
		margin-bottom: 10rpx;
	}

	.points {
		font-size: 30rpx;
		color: #aaa;
		/* font-weight: bold; */
		margin-left: 20rpx;
	}

	.action-buttons {
		display: flex;
		justify-content: flex-end;
	}

	.btn-view,
	.btn-action {
		border-radius: 50px;
		font-size: 28rpx;
		margin: 5px;
	}

	.btn-view {
		border: 1rpx solid #ddd;
		background-color: #fff;
		color: #666;
	}

	.btn-action {
		background-color: #FF6B00;
		color: #fff;

	}

	.btn-action-pending {
		background-color: #FF6B00;
	}

	.btn-action-completed {
		background-color: #8BC34A;
		border: 1px solid;
	}

	.btn-action:disabled {
		background-color: #ccc;
		cursor: not-allowed;
	}
</style>